package com.sync.utils.project.message.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * TODO
 *
 * @Author YWF
 * @Date 2023/8/31 17:36
 */
@Slf4j
public class MessageUtil {

    private static Map<String, SseEmitter> sseEmitterMap = new ConcurrentHashMap();

    private static AtomicInteger counter = new AtomicInteger(0);


    public static SseEmitter connect(String messageId){
        SseEmitter sseEmitter = null;
        try {
            // 设置超时时间，0表示不过期。默认30秒
            sseEmitter = new SseEmitter(0L);
            sseEmitter.onCompletion(() -> {
                // 回调方法
                System.out.println("回调方法执行了");
            });
            sseEmitter.onError(s->{
                System.out.println("报错了"+s);
            });
            sseEmitter.onTimeout(()->{
                System.out.println("超时了");
            });
            sseEmitterMap.put(messageId,sseEmitter);
            counter.getAndIncrement();
            return sseEmitter;
        } catch (Exception e) {
            log.info("创建新的sse连接异常，当前用户：{}", messageId);
        }
        return null;
    }


    public static void sendMessage(String messageId, String message){
        if (sseEmitterMap.containsKey(messageId)){
            try {
                sseEmitterMap.get(messageId).send(message);
            } catch (IOException e) {
                log.error("用户[{}]推送异常:{}", messageId, e.getMessage());
                removeUser(messageId);
            }
        }
    }

    private static void removeUser(String messageId) {
        sseEmitterMap.remove(messageId);
    }

}
